package bll

import (
	"context"

	"manager/event"
	"manager/model"
	"manager/model/entity"
	"manager/store"
	"manager/store/postgres"
	"time"
)

type battery struct {
	iBattery store.IBattery
}

var Battery = &battery{
	iBattery: postgres.Battery,
}

func (a *battery) init() func() {
	return func() {}
}

func (a *battery) onEvent(*event.Data) {}

// Create 创建
func (a *battery) Create(ctx context.Context, in *model.BatteryCreateRequest) (int64, error) {
	var (
		err error
	)

	// 构建创建现场数据
	c := buildBattery(in)
	_, err = a.iBattery.Create(ctx, c)
	return c.Id, err
}

// Update 更新
func (a *battery) Update(ctx context.Context, in *model.BatteryUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt

	if in.BatteryCode != nil {
		dict["battery_code"] = in.BatteryCode
	}

	if in.FirmwaresVersion != nil {
		dict["firmwares_version"] = in.FirmwaresVersion
	}

	if in.BatteryType != nil {
		dict["battery_type"] = in.BatteryType
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here
	return a.iBattery.Update(ctx, in.Id, dict)
}

// Delete 删除
func (a *battery) Delete(ctx context.Context, in *model.BatteryDeleteRequest) error {
	return a.iBattery.Delete(ctx, in.Id)
}

// List 列表查询
func (a *battery) List(ctx context.Context, in *model.BatteryListRequest) (*model.BatteryListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.Battery
		out   = &model.BatteryListResponse{}
	)

	if total, list, err = a.iBattery.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = model.BatterysEntityToDto(list)

	return out, nil
}

// Find 列表查询
func (a *battery) Find(ctx context.Context, in *model.BatteryInfoRequest) (*model.BatteryInfo, error) {
	var (
		err  error
		data *entity.Battery
		out  = &model.BatteryInfo{}
	)

	if data, err = a.iBattery.Find(ctx, in); err != nil {
		return nil, err
	}

	out = model.BatteryEntityToDto(data)
	return out, nil
}

// buildBattery 构建创建数据现场
func buildBattery(in *model.BatteryCreateRequest) *entity.Battery {
	// todo: check the entity is required
	return &entity.Battery{

		BatteryCode: in.BatteryCode,

		FirmwaresVersion: in.FirmwaresVersion,

		BatteryType: in.BatteryType,

		CreatedAt: time.Now().Unix(),

		UpdatedAt: time.Now().Unix(),
	}
}
